package cc.wsyw126.java.mongoDB.Utils;

import com.mongodb.client.MongoCollection;
import org.bson.Document;

import java.util.*;

/**
 * Created by junpeng.yang on 17/1/9.
 */
public class MongoDB {

    /**
     * 1. 创建文档 org.bson.Document 参数为key-value的格式
     * 2. 创建文档集合List<Document>
     * 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List<Document>) 插入单个文档可以用 mongoCollection.insertOne(Document)
     */
    public Integer insertMany(MongoCollection<Document> documentMongoCollection, List<Object> objects) throws Exception {
        if (!CommonUtils.isEmpty(objects)) {

        }
        //插入文档
        List<Document> documents = new ArrayList<>();
        for (Object object : objects) {
            Document document = new Document();
            Map<String, Object> objectMap = ReflectBeanUtils.objectToMap(object);
            for (Map.Entry<String, Object> stringObjectEntry : objectMap.entrySet()) {
                document.put(stringObjectEntry.getKey(), stringObjectEntry.getValue());
            }
            documents.add(document);
        }
        documentMongoCollection.insertMany(documents);
        return objects.size();
    }

    public Integer insertOne(MongoCollection<Document> documentMongoCollection, Object object) throws Exception {
        this.insertMany(documentMongoCollection, new ArrayList<>(Arrays.asList(object)));
        return 1;
    }

    /**
     * 将is_delete字段置为1
     */
    private void delete(MongoCollection<Document> documentMongoCollection, List<Object> objects) throws Exception {
        // TODO: 17/1/9 写删除操作
    }
}
